<?php

class EpicController extends Zend_Controller_Action {

    const NEW_MODULE_BASE_URL = "http://epic.vn/moi?";
    const NEVER_DIE_MODULE_BASE_URL = "http://epic.vn/bat-hu?";
    const FUNNY_MODULE_BASE_URL = "http://epic.vn/k/haihuoc?";
    const IDEAS_MODULE_BASE_URL = "http://epic.vn/k/sangtao?";
    const MEME_MODULE_BASE_URL = "http://epic.vn/k/meme?";
    const RAGECOMIC_MODULE_BASE_URL = "http://epic.vn/k/ragecomics?";
    const GAMING_MODULE_BASE_URL = "http://epic.vn/k/gaming?";
    const SPORT_MODULE_BASE_URL = "http://epic.vn/k/the-thao?";
    const STORY_TRANS_MODULE_BASE_URL = "http://epic.vn/k/truyen-dich?";
    const METHOD_NEW = "new";
    const METHOD_NEVER = "never";
    const METHOD_FUNNY = "funny";
    const METHOD_IDEAS = "ideas";
    const METHOD_MEME = "meme";
    const METHOD_RAGECOMIC = "rage";
    const METHOD_GAMING = "gaming";
    const METHOD_SPORT = "sport";
    const METHOD_STORY_TRANS = "trans";
    const BASE_URL = "http://epic.vn/";

    private function getBaseUrl($method) {
        switch ($method) {
            case static::METHOD_NEW:
                return static::NEW_MODULE_BASE_URL;
                break;
            case static::METHOD_NEVER:
                return static::NEVER_DIE_MODULE_BASE_URL;
                break;
            case static::METHOD_FUNNY:
                return static::FUNNY_MODULE_BASE_URL;
                break;

            case static::METHOD_IDEAS:
                return static::IDEAS_MODULE_BASE_URL;
                break;
            case static::METHOD_MEME:
                return static::MEME_MODULE_BASE_URL;
                break;
            case static::METHOD_RAGECOMIC:
                return static::RAGECOMIC_MODULE_BASE_URL;
                break;

            case static::METHOD_GAMING:
                return static::GAMING_MODULE_BASE_URL;
                break;
            case static::METHOD_SPORT:
                return static::SPORT_MODULE_BASE_URL;
                break;
            case static::METHOD_STORY_TRANS:
                return static::STORY_TRANS_MODULE_BASE_URL;
                break;

            default:
                break;
        }
    }

    private static $memcache;
    private static $query_cache;

    public function __construct(\Zend_Controller_Request_Abstract $request, \Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) {
        parent::__construct($request, $response, $invokeArgs);
        /*$frontendoptions = array(
            'lifetime' => 60 * 15, // 15minutes
            'automatic_serialization' => true
        );
        $backendoptions = array(
            'cache_dir' => sys_get_temp_dir(),
            'file_name_prefix' => 'zend_cache_query_epic',
            'hashed_directory_level' => 2
        );
        self::$query_cache = Zend_Cache::factory('Core', 'File', $frontendoptions, $backendoptions);
        if (Haibl_ConfigData::SUPPORT_MEMCACHED) {
            self::$memcache = new Memcache;
            self::$memcache->connect(Haibl_ConfigData::DOMAIN, Haibl_ConfigData::PORT) or die("Could not connect");
        }*/
    }

    public function getAccessMemcachedKey() {
        $params = $this->_request->getParams();
        $requestParams = '';
        foreach ($params as $key => $value) {
            if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                $requestParams.= $key . '=' . $value;
            }
        }
        $action = $this->_request->getActionName();
        return md5($action . $requestParams);
    }

    public function checkAccessKeyParams() {
        $id = $this->_request->getParam("id");
        $appid = $this->_request->getParam("key");
        $sig = $this->_request->getParam("sig");
        $method = $this->_request->getParam("method");
        if ($appid == "" || $sig == "" || $id == "" || $method == "") {
            echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$INVAILD_PARAMS);
            return false;
        } else {
            if ($appid != Haibl_ConfigData::KEY) {
                echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                return false;
            } else {
                $params = $this->_request->getParams();
                $requestParams = '';
                foreach ($params as $key => $value) {
                    if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                        $requestParams.= $key . '=' . $value;
                    }
                }
                $requestParams.= Haibl_ConfigData::ACCESS_KEY;
                $encryptParams = md5($requestParams);

                if ($encryptParams == $sig) {
                    return true;
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                    if (Haibl_ConfigData::DEBUG) {
                        echo "<p>encryptParams = " . $encryptParams . "</p>";
                    }
                    return false;
                }
            }
        }
    }

    public function indexAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $isAccess = $this->checkAccessKeyParams();
        if ($isAccess) {

            $method = $this->_request->getParam("method") == "" ? "new" : $this->_request->getParam("method");
            $page = $this->_request->getParam("page") == "" ? 1 : $this->_request->getParam("page");
            $lastId = $this->_request->getParam("id") == "" ? 1 : $this->_request->getParam("id");

            $key = $this->getAccessMemcachedKey();
            $memCachedData = null;
            if (Haibl_ConfigData::SUPPORT_MEMCACHED)
                self::$memcache->get($key);
            if ($memCachedData != null) {
                echo json_encode($memCachedData);
            } else {
                $lists = null;
                if ($method == "new") {
                    //fix tam, epic da doi giao dien
                    if ($lastId == "-1") {
                        $baseUrl = "http://epic.vn/tag/photo";
                    } else {
                        $baseUrl = "http://epic.vn/tag/photo/" . $lastId;
                    }
                    $lists = $this->getImageListsNewStyle($baseUrl);
                } else {
                    $baseUrl = $this->getBaseUrl($baseUrl);
                    if ($baseUrl != "") {
                        $baseUrl .= "page=" . $page;
                        $lists = $this->getImageLists($baseUrl);
                    }
                }

                $returnData = array();
                if ($lists != null && !empty($lists)) {
                    $returnData['errorId'] = Sunny_ErrorHandled::$DONE;
                    $returnData['data'] = $lists;
                    if (Haibl_ConfigData::SUPPORT_MEMCACHED)
                        self::$memcache->set($key, $returnData, false, Haibl_ConfigData::CACHED_KEEP_ALIVE) or die("Failed to save data at the server");
                    echo json_encode($returnData);
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$PAGE_NOT_FOUND);
                }
            }
        }
    }

    function getImageListsNewStyle($baseUrl) {
        $key = $this->getAccessMemcachedKey();
        if (true) {
            $client = new Zend_Http_Client();
            $client->setUri($baseUrl);
            $response = $client->request();
            $html = $response->getBody();

            $dom = new Zend_Dom_Query($html);
            $results = $dom->query('.post');

            $data = array();
            $dataIndex = 0;

            $results->rewind();

            while ($results->valid()) {

                $domDoc = $results->current();

                $DOMNodeList = $domDoc->getElementsByTagName("a");
                if ($DOMNodeList->length > 0) {
                    for ($i = 0; $i < $DOMNodeList->length; $i++) {
                        $element = $DOMNodeList->item($i);
                        $class = $element->getAttribute("class");
                        if ("permalink" == $class) {
                            $data[$dataIndex]['img'] = $element->getAttribute("href");
                            $data[$dataIndex]['postime'] = $element->getAttribute("title");
                        }
                    }
                }

                $DOMNodeList = $domDoc->getElementsByTagName("div");
                if ($DOMNodeList->length > 0) {
                    for ($i = 0; $i < $DOMNodeList->length; $i++) {
                        $element = $DOMNodeList->item($i);
                        $class = $element->getAttribute("class");
                        if ("post_info" == $class) {
                            $data[$dataIndex]['uploader'] = trim($element->nodeValue);
                        }
                    }
                }

                $DOMNodeList = $domDoc->getElementsByTagName("img");
                if ($DOMNodeList->length > 0) {
                    $data[$dataIndex]['src'] = $DOMNodeList->item(0)->getAttribute("src");
                }

                $DOMNodeList = $domDoc->getElementsByTagName("p");
                if ($DOMNodeList->length > 0) {
                    $data[$dataIndex]['title'] = $DOMNodeList->item(0)->nodeValue;
                }

                $data[$dataIndex]['view'] = "0";
                $data[$dataIndex]['comment'] = "0";
                $data[$dataIndex]['like'] = "0";

                $dataIndex++;
                $results->next();
            }
            //self::$query_cache->save($data, $key);
            return $data;
        } else {
            return $result;
        }
    }

    function getImageLists($baseUrl) {
        $client = new Zend_Http_Client();
        $client->setUri($baseUrl);
        $response = $client->request();
        $html = $response->getBody();

        $dom = new Zend_Dom_Query($html);
        $results = $dom->query('.gag-link');

        $data = array();
        $dataIndex = 0;

        $results->rewind();
        while ($results->valid()) {
            $domDoc = $results->current();

            $DOMNodeList = $domDoc->getElementsByTagName("a");
            if ($DOMNodeList->length > 0) {
                $data[$dataIndex]['href'] = $DOMNodeList->item(0)->getAttribute("href");
                $data[$dataIndex]['title'] = trim($DOMNodeList->item(1)->nodeValue);
                $data[$dataIndex]['uploader'] = trim($DOMNodeList->item(2)->getAttribute("href"));
            }

            $DOMNodeList = $domDoc->getElementsByTagName("img");
            if ($DOMNodeList->length > 0) {
                $data[$dataIndex]['src'] = $DOMNodeList->item(0)->getAttribute("src");
                $data[$dataIndex]['bigsrc'] = $data[$dataIndex]['src'];
            }

            $DOMNodeList = $domDoc->getElementsByTagName("p");
            if ($DOMNodeList->length > 0) {
                $data[$dataIndex]['postime'] = $DOMNodeList->item(0)->nodeValue;
            }

            $DOMNodeList = $domDoc->getElementsByTagName("span");
            if ($DOMNodeList->length > 0) {
                $data[$dataIndex]['like'] = $DOMNodeList->item(1)->nodeValue;
            }
            $dataIndex++;
            $results->next();
        }
        return $data;
    }

}
?>

